<template>
  <div class="resource-manage">
    <div class="card-box">
      <div :class="`${requiredJudge[0] && type == 'edit'?'required':''} card-title`" v-if="type == 'edit' ? true : firstFiles.length">{{firstTitle}}</div>
      <div class="uploadItem">
        <v-upload
          ref="uploadFir"
          url="/admin/sys-file/upLodeFileEdit"
          :busId="busId"
          modelType="budgetApply"
          @onSuccess="onSuccess"
          @loadCompleted="handleFirLoaded"
          v-model="uploadFileListFir"
          isShowFileList
          :canDelete="type === 'edit'"
          :isView="type === 'preview'"
          :autoLoadFiles="false"
          :hideExplain="type === 'preview'"
        />
      </div>
      <div :class="`${requiredJudge[1] && type == 'edit'?'required':''} card-title`" v-if="type == 'edit' ? true : secondFiles.length">{{secondTitle}}</div>
      <div class="uploadItem">
        <v-upload
          ref="uploadSec"
          url="/admin/sys-file/upLodeFileEdit"
          :busId="fileId"
          modelType="businessBasis"
          @onSuccess="onSuccess"
          @loadCompleted="handleSecLoaded"
          v-model="uploadFileListSec"
          isShowFileList
          :canDelete="type === 'edit'"
          :isView="type === 'preview'"
          :autoLoadFiles="false"
          :hideExplain="type === 'preview'"
        />
      </div>
    </div>
  </div>
</template>

<script>

export default {
  name: 'fileUpload',
  props: {
    // 附件业务ID
    busId: {
      type: String,
      default: ''
    },
    // 凭据业务id
    fileId: {
      type: [String, Object],
      default: ''
    },
    // 是否需要必填
    required: {
      type: [Boolean, Array],
      default: true
    },
    // 最大上传数量(为0不限制上传数量)
    maxFiles: {
      type: [Number, String],
      default: 0
    },
    // 展示类型（分preview和edit两种模式，预览模式时隐藏上传按钮和文字说明）
    type: {
      type: String,
      default: 'preview',
      validator: val => ['preview', 'edit'].includes(val)
    },
    // 第一个附件标题
    firstTitle: {
      type: String,
      default: '附件材料'
    },
    // 第二个附件标题
    secondTitle: {
      type: String,
      default: '业务依据'
    }
  },
  mounted () {
    this.init()
  },
  data () {
    return {
      // 附件材料文件列表
      uploadFileListFir: [],
      // 业务依据文件列表
      uploadFileListSec: [],
      // 完成上传的数组
      completedNum: 0,
      // 暂存文件id
      temporaryId: '',
      // 第一个附件的文件数量
      firstFiles: [],
      // 第一个附件的文件数量
      secondFiles: [],
    }
  },
  computed: {
    // 必填判断
    requiredJudge () {
      if (typeof this.required === "boolean") {
        return [this.required, this.required]
      }
      return this.required
    },
    // 上传次数判断
    uploadCalc () {
      if (this.uploadFileListFir.length && this.uploadFileListSec.length) {
        return 2
      } else if (this.uploadFileListFir.length || this.uploadFileListSec.length) {
        return 1
      }
      return 0
    },
  },
  methods: {
    //初始化
    init () {
      this.busId && this.$refs.uploadFir.getFiles(this.busId)
      this.fileId && this.$refs.uploadSec.getFiles(this.fileId)
    },
    // 上传
    submit () {
      if (this.validator()) {
        if (this.uploadFileListFir.length + this.uploadFileListSec.length == 0) {
          this.$emit('onSuccess')
        } else {
          this.uploadFileListFir.length && this.$refs.uploadFir.submit('budgetApply', this.busId);
          this.uploadFileListSec.length && this.$refs.uploadSec.submit('businessBasis', this.fileId || '');
        }
      }
    },
    // 上传校验
    validator () {
      // 必传校验
      if (this.requiredJudge[0] && (this.$refs.uploadFir.loadFileList.length + this.$refs.uploadFir.fileList.length == 0)) {
        this.$message.error(`${this.firstTitle}不能为空`)
        return false
      } else if (this.requiredJudge[1] && this.$refs.uploadSec.loadFileList.length + this.$refs.uploadSec.fileList.length == 0) {
        this.$message.error(`${this.secondTitle}不能为空`)
        return false
      }
      // 最大上传数量校验
      if (this.maxFiles > 0) {
        if (this.$refs.uploadFir.loadFileList.length + this.$refs.uploadFir.fileList.length > this.maxFiles) {
          this.$message.error(`${this.firstTitle}上传数量不能超过${this.maxFiles}条`)
          return false
        } else if (this.$refs.uploadSec.loadFileList.length + this.$refs.uploadSec.fileList.length > this.maxFiles) {
          this.$message.error(`${this.secondTitle}上传数量不能超过${this.maxFiles}条`)
          return false
        }
        return true
      }
      return true
    },
    // 上传成功
    onSuccess (response, file, fileList) {
      //先判断field是否存在,存在的话，直接判断上传完成,完成直接emit上报，未完成+1
      // fieldId不存在的话,判断response.data是否等于this.busId
      // 等于的话，判断当前上传是否完成，完成直接emit上报，未完成+1
      // 不等于的话，暂存的 response.data, 判断完成，完成emit带上暂存id提交 ，未完成，暂存response.data
      if (this.fileId) {
        this.uploadCalc === this.completedNum ? this.$emit('onSuccess', response.data) : (this.completedNum += 1)
      } else {
        if (response.data == this.busId) {
          this.uploadCalc === (this.completedNum + 1) ? this.$emit('onSuccess') : (this.completedNum += 1)
        } else {
          this.temporaryId = response.data
          this.$nextTick(() => {
            this.uploadCalc === (this.completedNum + 1) ? this.$emit('onSuccess', this.temporaryId) : (this.completedNum += 1)
          })
        }
      }
    },
    // 监听组件加载成功
    handleFirLoaded (data) {
      this.firstFiles = data
    },
    // 同上
    handleSecLoaded (data) {
      this.secondFiles = data
    },
  },
}
</script>

<style lang="scss" scoped>
.resource-manage .card-box {
  padding: 0 22px;
  & > .required {
    position: relative;
    &::before {
      content: "*";
      color: #f56c6c;
      position: absolute;
      left: 0.25em;
      top: 0;
      width: 1em;
      text-align: center;
    }
  }
  .uploadItem {
    padding: 12px 20px;
  }
}
</style>
